package com.uetoken.cn.activity;

import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.uetoken.cn.R;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.utils.CompareNumberSizeUtils;
import com.uetoken.cn.utils.CountDownTimerUtils;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 免密支付
 */
public class SecretPaymentActivity extends BaseActivity implements WebResponse{

    @BindView(R.id.iv_back)
    ImageView    mIvBack;
    @BindView(R.id.tv_title)
    TextView     mTvTitle;
    @BindView(R.id.switch_activity_secret_payment)
    Switch       mSwitch;
    @BindView(R.id.edt_activity_secret_payment_secret_amount)
    EditText     mEdtecretAmount;
    @BindView(R.id.edt_activity_secret_payment_phone)
    EditText     mEdtPhone;
    @BindView(R.id.tv_activity_register_get_auth_code)
    TextView     mTvGetAuthCode;
    @BindView(R.id.edt_activity_secret_payment_auth_code)
    EditText     mEdtInputAuthCode;
    @BindView(R.id.ll_activity_secret_payment_content)
    LinearLayout mLlContent;
    @BindView(R.id.tv_activity_secret_payment_confirm_open)
    TextView     mTvConfirmOpen;
    @BindView(R.id.tv_activity_secret_payment_amount)
    TextView    mTvSecretAmount;
    /**
     * 获取验证码的网络请求码
     */
    private static final int NETWORK_REQUEST_GET_AUTH_CODE       = 10;
    /**
     * 开通免密支付的网络请求码
     */
    private static final int NETWORK_REQUEST_OPEN_SECRET_PAYMENT = 20;
    /**
     * 关闭免密支付开关后调用免密支付接口的网络请求码
     */
    private static final int NETWORK_REQUEST_OPEN_SECRET_PAYMENT_CLOSE_SWITCH = 30;
    private CountDownTimerUtils countDownTimerUtils;

    @Override
    public int getLayoutId() {
        return R.layout.activity_secret_payment;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        /*状态栏沉浸式*/
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, android.R.color.white), true);
        BarUtils.setStatusBarLightMode(this, true);

        mIvBack.setVisibility(View.VISIBLE);
        mTvTitle.setText(getResources().getString(R.string.str_open_secret_payment));

    }

    @Override
    public void initData() {
        String mobileNo = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_MOBILE_NO, "");

        final String secretAmount = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_MAXIMUM_SECRET_AMOUNT, "0");

        if (CompareNumberSizeUtils.compare(secretAmount,"0")==0){
            //免密支付金额等于0关闭按钮
            mSwitch.setChecked(false);
            mTvSecretAmount.setVisibility(View.GONE);
            mLlContent.setVisibility(View.GONE);
            mTvConfirmOpen.setVisibility(View.GONE);
        }else{
            mSwitch.setChecked(true);
            mTvSecretAmount.setVisibility(View.VISIBLE);
            mLlContent.setVisibility(View.GONE);
            mTvConfirmOpen.setVisibility(View.GONE);
            mTvSecretAmount.setText(String.format(getResources().getString(R.string.str_current_secret_amount_maximum),secretAmount));
        }
        mEdtPhone.setText(mobileNo);

        mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    //打开状态
                    String secret = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_MAXIMUM_SECRET_AMOUNT, "0");
                    if (CompareNumberSizeUtils.compare(secret,"0")>0){
                        mTvSecretAmount.setVisibility(View.VISIBLE);
                        mLlContent.setVisibility(View.GONE);
                        mTvConfirmOpen.setVisibility(View.GONE);
                        mTvSecretAmount.setText(String.format(getResources().getString(R.string.str_current_secret_amount_maximum),secret));
                    }else{
                        mTvSecretAmount.setVisibility(View.GONE);
                        mLlContent.setVisibility(View.VISIBLE);
                        mTvConfirmOpen.setVisibility(View.VISIBLE);
                    }
                }else{
                    //关闭按钮调用接口设置免密支付金额为0
                    secrectPayment("0","",NETWORK_REQUEST_OPEN_SECRET_PAYMENT_CLOSE_SWITCH);
                }
            }
        });

    }

    @Override
    public void init() {

    }


    @OnClick({R.id.iv_back, R.id.tv_activity_register_get_auth_code, R.id.tv_activity_secret_payment_confirm_open})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_activity_register_get_auth_code:
                getAuthCode();
                break;
            case R.id.tv_activity_secret_payment_confirm_open:
                openSecretPayment();
                break;
        }
    }


    /**
     * 获取验证码
     */
    private void getAuthCode() {
        String phone = mEdtPhone.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_be_empty));
            return;
        }
        if (!RegexUtils.isMobileSimple(phone)) {
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_specification));
            return;
        }
        countDownTimerUtils = new CountDownTimerUtils(this, mTvGetAuthCode, 60000, 1000);
        countDownTimerUtils.start();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getSendSMSUrl(), NETWORK_REQUEST_GET_AUTH_CODE, Params.getSmsParams(phone));

    }

    /**
     * 开通免密支付
     */
    private void openSecretPayment() {
        String amount = mEdtecretAmount.getText().toString().trim();
        String phone = mEdtPhone.getText().toString().trim();
        String authCode = mEdtInputAuthCode.getText().toString().trim();
        if (TextUtils.isEmpty(amount)){
            ToastUtils.showShort(getResources().getString(R.string.str_secret_amount_not_empty));
            return;
        }
        if (Integer.parseInt(amount)>500){
            ToastUtils.showShort(getResources().getString(R.string.str_secret_amount_less_than));
            return;
        }
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_be_empty));
            return;
        }
        if (!RegexUtils.isMobileSimple(phone)) {
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_specification));
            return;
        }
        if (TextUtils.isEmpty(authCode)){
            ToastUtils.showShort(getResources().getString(R.string.str_auth_code_not_empty));
            return;
        }
        secrectPayment(amount,authCode,NETWORK_REQUEST_OPEN_SECRET_PAYMENT);
    }

    /**
     * 开通免密支付
     */
    private void secrectPayment(String amount,String authCode,int requstCode) {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getModifyUserInfoUrl(),requstCode,
                Params.getModifyUserInfoParams("6",amount,authCode));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimerUtils != null) {
            countDownTimerUtils.cancel();
        }
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        switch (requestCode){
            case NETWORK_REQUEST_GET_AUTH_CODE:
                break;
            case NETWORK_REQUEST_OPEN_SECRET_PAYMENT:
                dissmissDialog();
                JsonObject obj = new JsonParser().parse(response).getAsJsonObject();
                String message = obj.get("message").getAsString();
                if (obj.get("result").getAsInt() > 0) {
                    //设置最大免密金额成功后保存免密金额
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_MAXIMUM_SECRET_AMOUNT,mEdtecretAmount.getText().toString().trim());
                    ToastUtils.showShort(message);
                    finish();
                } else {
                    ToastUtils.showShort(message);
                }
                break;
            case NETWORK_REQUEST_OPEN_SECRET_PAYMENT_CLOSE_SWITCH:
                //关闭按钮后服务器和本地的免密金额都变为0
                dissmissDialog();
                JsonObject obj1 = new JsonParser().parse(response).getAsJsonObject();
                String message1 = obj1.get("message").getAsString();
                if (obj1.get("result").getAsInt() > 0) {
                    //设置最大免密金额成功后保存免密金额为0
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_MAXIMUM_SECRET_AMOUNT,"0");

                    mTvSecretAmount.setVisibility(View.GONE);
                    mLlContent.setVisibility(View.GONE);
                    mTvConfirmOpen.setVisibility(View.GONE);
                } else {
                    ToastUtils.showShort(message1);
                }
                break;
        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
    }
}
